// const response  = require("express");
const express = require("express");
const cors = require("cors");
const fs = require("fs");

const app = express();

const {Server} = require("socket.io");

const httpServer = app.listen(3000, function(){
    console.log("server started at http://127.0.0.1:3000")
});

const socketServer = new Server(httpServer);

socketServer.on("connect", (socket)=>{
    console.log("connect: " + socket.id);

    socket.on("user", (id, cb)=>{
        console.log(id);
        const user = {
            name: "吉良 吉影",
            age: 33,
    
        };
    
        fs.readFile("./_cover.jpg", (err, data)=>{
            if(err){
                cb({result: false, message: "数据读取失败"});
            }else{
                user.avatar = data.toString("base64");
                cb({result: true, message: "数据获取成功", data: user});
            }
        });
    })
    // socketServer.to(socket.id).emit();           // 参数为房间名， 给指定房间名中所有客户端发消息
    // socketServer.join(/* room */);               // 将socket加入某房间，参数为指定房间   默认自己的房间为自己的id
})

let num = 0; 

setInterval(()=>{
    socketServer.emit("count", ++num);
}, 2000)

// app.use(cors({
//     credentials: true,
//     optionsSuccessStatus: 200,
//     origin: "http://127.0.0.1:5500"
// }))

app.use(express.static('./public'))

app.get("/user2", (request, response)=>{
    const user = {
        name: "吉良 吉影",
        age: 33,

    };

    fs.readFile("./1.bmp", (err, data)=>{
        if(err){
            response.sendStatus(500);
        }else{
            user.avatar = data.toString("base64");
            response.send(user);
        }
    });
    
});

